package com.mybatis.demo.controller;

import com.mybatis.demo.domain.Attendence;
import com.mybatis.demo.domain.Student;
import com.mybatis.demo.service.AttendanceService;
import com.mybatis.demo.service.StudentService;
import com.mybatis.demo.tools.CommonResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.sql.Date;
import java.util.*;

@RestController
@RequestMapping("/kaoqin")
@CrossOrigin
@Tag(name = "KaoqinController", description = "考勤接口")
public class KaoqinController {

    @Autowired
    private AttendanceService attendanceService;
    @Autowired
    private StudentService studentService;

    @GetMapping("/searchStu")
    @Operation(summary = "查询所有学生信息")
    public CommonResult searchStu(Long page, Long size, String studentName) {
        Map<String, Object> map = new HashMap<>();
        map.put("total", studentService.count(studentName));
        map.put("rows", studentService.searchAll(page, size, studentName));
        return CommonResult.success(map, "查询成功");
    }

    @PostMapping("/add")
    @Operation(summary = "添加考勤信息")
    public CommonResult addStu(@RequestBody Attendence attendence) {
        return CommonResult.success(attendanceService.InsertAttendenceBydate(attendence), "添加成功");
    }

    @PutMapping("/update")
    @Operation(summary = "更新考勤信息")
    public CommonResult updateStu(@RequestBody Attendence attendence) {
        return CommonResult.success(attendanceService.UpdateAttendence(attendence), "更新成功");
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除考勤信息")
    public CommonResult deleteStu(@PathVariable("id") Long id) {
        return CommonResult.success(attendanceService.delById(id), "删除成功");
    }

    @GetMapping("/search")
    @Operation(summary = "查询考勤信息")
    public CommonResult search(Long page, Long size, String name, Date date) {
        Map<String, Object> map = new HashMap<>();
        map.put("total", attendanceService.count(name,date));
        map.put("rows", attendanceService.SearchAttendence(page, size, name, date));
        return CommonResult.success(map, "查询成功");
    }
    @GetMapping("/searchById")
    @Operation(summary = "查询考勤信息")
    public CommonResult searchById(Long page, Long size, Long id, Date date) {
        Map<String, Object> map = new HashMap<>();
        map.put("total", attendanceService.countById(id));
        map.put("rows", attendanceService.SearchAttendenceBystuId(page, size, id, date));
        return CommonResult.success(map, "查询成功");
    }
    @DeleteMapping("/deleteStuByid/{id}")
    @Operation(summary = "删除学生信息")
    public CommonResult deleteStuByid(@PathVariable("id") Long id) {
        return CommonResult.success(studentService.deleteStu(id), "删除成功");
    }
    @PostMapping("/addStu")
    @Operation(summary = "添加学生信息")
    public CommonResult addStu(@RequestBody Student student) {
        return CommonResult.success(studentService.addStu(student), "添加成功");
    }
    @PutMapping("/updateStu")
    @Operation(summary = "更新学生信息")
    public CommonResult updateStu(@RequestBody Student student) {
        return CommonResult.success(studentService.updateStu(student), "更新成功");
    }
    @PostMapping("/upload")
    @Operation(summary = "上传图片")
    public CommonResult uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            // 1. 验证文件是否为空
            if (file == null || file.isEmpty()) {

                return CommonResult.failed("请选择要上传的文件");
            }

            // 2. 验证文件类型
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                return CommonResult.failed("文件名不能为空");
            }

            String extension = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
            if (!Arrays.asList(".jpg", ".jpeg", ".png", ".gif", ".bmp").contains(extension)) {
                return CommonResult.failed("只支持 jpg、jpeg、png、gif、bmp 格式的图片");
            }

            // 3. 验证文件大小 (5MB = 5 * 1024 * 1024 bytes)
            long maxSize = 5 * 1024 * 1024;
            if (file.getSize() > maxSize) {
                return CommonResult.failed("文件大小不能超过5MB");
            }

            // 4. 创建上传目录
            String uploadDir = "uploads/images/";
            // 获取项目根路径
            String projectPath = System.getProperty("user.dir");
            String fullUploadPath = projectPath + File.separator + uploadDir;

            File uploadDirectory = new File(fullUploadPath);
            if (!uploadDirectory.exists()) {
                uploadDirectory.mkdirs();
            }

            // 5. 生成唯一文件名
            String fileName = originalFilename;

            // 6. 保存文件
            File destinationFile = new File(fullUploadPath + fileName);
            file.transferTo(destinationFile);

            // 7. 生成访问URL
            String fileUrl = "http://localhost:9527/" + uploadDir + fileName;

            // 8. 返回成功结果
            Map<String, Object> result = new HashMap<>();
            result.put("fileName", fileName);
            result.put("originalName", originalFilename);
            result.put("fileUrl", fileUrl);
            result.put("fileSize", file.getSize());

            return CommonResult.success(result, "文件上传成功");

        } catch (IOException e) {
            e.printStackTrace();
            return CommonResult.failed("文件上传失败：" + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("系统错误：" + e.getMessage());
        }
    }



}
